package com.coocaa.internship.service.serviceImpl;

import com.coocaa.internship.service.SMSService;
import com.coocaa.internship.util.RedisUtil;
import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.httpclient.HTTPException;
import lombok.NonNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Random;

/**
 * @Description:
 * @Author: 凌贤
 * @Date: 2019-07-30
 * @Time: 10:29
 */
@Service
public class SMSservicelmpl implements SMSService {
    @Autowired
    RedisUtil redisUtil;

    final int appid = 1400240478;
    final String appkey = "289b82894c12f5e10768ffcb92a8da7e";
    final int tempId = 391919;
    final String smsMsg = "青柠学姐";
    @Override
    public String CodeSend(@NonNull String telephoneNumber) throws HTTPException, IOException {
        Random random = new Random(System.currentTimeMillis());
        int code;
        while (true) {
            code = random.nextInt(999999);
            if (code > 100000) {
                break;
            }
        }
        String[] codes = new String[1];
        codes[0] = String.valueOf(code);

        SmsSingleSender smsSingleSender = new SmsSingleSender(appid, appkey);
        smsSingleSender.sendWithParam("86", telephoneNumber, tempId, codes, smsMsg, "", "");
        redisUtil.set(telephoneNumber, codes[0], 180);
        return String.valueOf(code);
    }

    @Override
    public boolean CodeValidate(@NonNull String code, @NonNull String telephoneNumber) {
        if (redisUtil.get(telephoneNumber) == null) {
            return false;
        } else {
            return redisUtil.get(telephoneNumber).equals(code);
        }
    }

}
